//被围绕的区域
class Solution {
    int m, n;
    int dx[4] = {0, 0, 1, -1};
    int dy[4] = {1, -1, 0, 0};
    bool vis[201][201];
    typedef pair<int, int> PII;

public:
    void solve(vector<vector<char>>& board) {
        m = board.size();
        n = board[0].size();
        for (int i = 0; i < m; i++)
            bfs(board, i, 0);
        for (int i = 0; i < m; i++)
            bfs(board, i, n - 1);
        for (int i = 0; i < n; i++)
            bfs(board, 0, i);
        for (int i = 0; i < n; i++)
            bfs(board, m - 1, i);
        for (int i = 0; i < m; i++)
            for (int j = 0; j < n; j++)
                if (!vis[i][j])
                    board[i][j] = 'X';

        return;
    }
    void bfs(vector<vector<char>> board, int i, int j) {
        if (board[i][j] == 'X' || vis[i][j])
            return;
        queue<PII> q;
        q.push({i, j});
        vis[i][j] = true;
        while (q.size()) {
            auto [a, b] = q.front();
            q.pop();
            for (int k = 0; k < 4; k++) {
                int x = a + dx[k];
                int y = b + dy[k];
                if (x >= 0 && x < m && y >= 0 && y < n && board[x][y] == 'O' &&
                    !vis[x][y]) {
                    vis[x][y] = true;
                    q.push({x, y});
                }
            }
        }
        return;
    }
};

//迷宫中离入口最近的出口
class Solution {
    int m, n;
    int dy[4] = {1, -1, 0, 0};
    int dx[4] = {0, 0, 1, -1};
    bool vis[101][101];
    typedef pair<int, int> PII;

public:
    int nearestExit(vector<vector<char>>& maze, vector<int>& entrance) {
        queue<PII> q;
        q.push({entrance[0], entrance[1]});
        vis[entrance[0]][entrance[1]] = true;
        m = maze.size();
        n = maze[0].size();
        int ret = 0;
        while (q.size()) {
            // cout<<m<<endl;
            int s = q.size();
            ret++;
            for (int j = 0; j < s; j++) {
                auto [a, b] = q.front();
                q.pop();
                for (int i = 0; i < 4; i++) {
                    int x = a + dx[i];
                    int y = b + dy[i];
                    if (x >= 0 && x < m && y >= 0 && y < n &&
                        maze[x][y] == '.' && !vis[x][y]) {
                        if (x == 0 || x == m - 1 || y == 0 || y == n - 1)
                            return ret;
                        vis[x][y] = true;
                        q.push({x, y});
                    }
                }
            }
        }
        return -1;
    }
};